package com.nirvana.admin.filter;

import cn.hutool.core.util.StrUtil;
import com.nirvana.admin.entity.vo.LoginUser;
import com.nirvana.admin.service.AuthService;
import com.nirvana.admin.util.SecurityUtils;
import com.nirvana.common.dto.BaseResponse;
import com.nirvana.common.intercepter.GlobalExceptionHandler;
import com.nirvana.common.util.ServletUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT 过滤器，验证 token 的有效性
 * 验证通过后，获得 {@link LoginUser} 信息，并加入到 Spring Security 上下文
 *
 * @author zsy
 */
@Component
@AllArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final AuthService authService;

    private final GlobalExceptionHandler globalExceptionHandler;

    @Override
    @SuppressWarnings("NullableProblems")
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String token = SecurityUtils.obtainAuthorization(request);

        if (StrUtil.isNotEmpty(token)) {
            try {
                // 验证 token 有效性
                LoginUser loginUser = authService.verifyTokenAndRefresh(token);
                // 模拟 Login 功能，方便日常开发调试
                if (loginUser == null) {
                    return;
                }
                // 设置当前用户
                SecurityUtils.setLoginUser(loginUser, request);
            } catch (Exception ex) {
                BaseResponse<?> result = globalExceptionHandler.handleException(ex);
                ServletUtils.writeJson(response, result);
                return;
            }
        }

        // 继续过滤链
        chain.doFilter(request, response);
    }
}
